<?php
/**
 * Created by PhpStorm.
 * User: jimmy
 * Date: 2017/8/9
 * Time: 下午9:06
 */

use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Regex as RegexValidator;
use Phalcon\Validation\Validator\Between;
use Phalcon\Validation\Validator\StringLength;

class PlaneController extends CloudControllerBase
{


    public function listMonitorAction()
    {

    }

    public function addMonitorAction()
    {

    }

    public function doMonitorListAction()
    {

    }

    /******************************    飞机列表    ***********************************************************/

    public function listAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {


                $table = "(
SELECT
	plane.id,
	plane.uas_serial_id,
	plane_model.name plane_model_name,
	plane.name,
	plane.company,
	plane.phone,
	plane_type.name plane_type_name,
	plane.type,
	plane.expired_at,
	plane.kilometer,
	plane.fuselage_end_at,
	plane.insurance_end_at,
	p.uas_odometer_value,
	plane.created_at,
	plane.planeModel_id
FROM
	plane
LEFT JOIN plane_type ON plane_type.id = plane.plane_type_id
LEFT JOIN plane_model ON plane_model.id = plane.planeModel_id
LEFT JOIN (
	SELECT
		uas_serial_id,
		max(uas_odometer_value) AS uas_odometer_value
	FROM
		uas_status
	GROUP BY
		uas_serial_id
) AS p ON p.uas_serial_id = plane.uas_serial_id
                )";
                $this->postQueryByPage(array(
                    "id" => "ID",
                    "uas_serial_id" => "飞机序列号",
                    "plane_model_name" => "飞机型号",
                    "name" => "持有单位",
                    "company" => "备注",
                    "phone" => "手机号码",
                    "plane_type_name" => "飞机状态",
                    "type" => "证书类型",
                    "expired_at" => "到期时限",
                    "kilometer" => "限制公里数",
                    "fuselage_end_at" => "机身险至",
                    "insurance_end_at" => "第三方险至",
                    "uas_odometer_value" => "飞控里程",
                    "created_at" => "创建时间"
                ), $table
                    , array(
                        ["uas_serial_id", "like", "%", "%"],
                        ["plane_type_id", "="],
                        ["phone", "like", "%", "%"],
                        ["planeModel_id", "="],
                        ["name", "like", "%", "%"],
                        ['fuselage_end_at_start', '>=', '', '', "fuselage_end_at"],
                        ['fuselage_end_at_end', '<=', '', '', "fuselage_end_at"],
                        ['insurance_end_at_start', '>=', '', '', "insurance_end_at"],
                        ['insurance_end_at_end', '<=', '', '', "insurance_end_at"]
                    ), "uas_serial_id desc", "uas_serial_id");
            };
                break;
        }
        $this->view->setVars(array("planeTypeList" => $this->getPlaneModelInfo()

            )

        );
    }


    /******************************    飞机详情    ***********************************************************/

    public function addPlaneAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        switch ($this->getRequestAction()) {
            case $this::REQUEST_ACTION_ADD: {
                $this->checkRequestParams(array(
                    array(
                        "key" => "uas_serial_id",
                        "type" => "presence",
                        "message" => "飞机序列号为空",
                    ),
                ));
                $uas_serial_id = $this->getPost("uas_serial_id");
                $total = $this->fetchOne("select count(*) as total from plane where uas_serial_id='$uas_serial_id'");
                if ($total['total'] <= 0) {
                    $this->insertSqlData(array(
                        "table" => "plane",
                        "fieldList" => array(
                            "uas_serial_id", "name", "phone", "plane_type_id", "expired_at",
                            "plane_area_id", "insurance", "insurance_begin_at", "fuselage_insurance",
                            "fuselage_begin_at", "planeModel_id", "name", "company",
                            "buy_at", "warranty_kilometer", "insurance_end_at", "fuselage_end_at"
                        )
                    ));
                    $this->returnSuccess("更新成功");
                } else {
                    $this->returnError("飞机已存在");
                }

            };
                break;
            default: {
                $this->view->setVars(array(
                    "planeModelList" => $this->getPlaneModelInfo(),
                    "planeTypeList" => $this->getPlaneTypeInfo(),
                    "planeAreaList" => $this->getPlaneAreaInfo()));
            };
                break;
        }
    }

    public function detailAction()
    {

        $user = $this->getMonitorLoginUser();
        $action = $this->getRequestAction();
        switch ($action) {
            case $this::REQUEST_ACTION_DETAIL: {

                $planeId = $this->getPost("plane_id");
                $planeUasId = $this->getPost("plane_uid");
                if ($planeUasId) {
                    $sql = "select * from plane where uas_serial_id='$planeUasId'";
                }
                if ($planeId) {
                    $sql = "select * from plane where id=$planeId";
                }
                if (!$sql) {
                    $this->returnError("请求参数错误");
                }
                $planeData = $this->fetchOne($sql);
                if ($planeData) {
                    $planeId = $planeData["id"];
                    $keyCounts =$this->fetchOne("select count(*) as count from plane_key as k ,plane as p where k.plane_id=p.id and k.plane_id=$planeId group by plane_id");
                    if ($keyCounts['count'] > 1) {
                        $keySql = "select k.* from plane_key as k ,plane as p where k.plane_id=p.id and p.key_id=k.key_id and k.plane_id=$planeId";
                    } else {
                        $keySql = "select k.* from plane_key as k ,plane as p where k.plane_id=p.id and k.plane_id=$planeId group by plane_id";
                    }
                    $keyData = $this->fetchOne($keySql);
                    $this->returnJson(array(
                        "plane" => $planeData,
                        "key" => $keyData
                    ));
                } else {
                    $this->returnError("该飞机编号未被录入到数据库中");
                }


            };
                break;
            case $this::REQUEST_ACTION_UPDATE: {
                if (!$this->isMonitorAdminUser()) {
                    $this->returnAuthError("您没有操作权限");
                }
                $this->checkRequestParams(array(
                    array(
                        "key" => "taget_plane_id",
                        "type" => "presence",
                        "message" => "飞机id为空")
                ));
                $targetPlaneId = $this->getPost("taget_plane_id");
                $total = $this->fetchOne("select count(*) as total from plane where id=$targetPlaneId");
                if ($total['total'] <= 0) {
                    $this->returnError("不存在该飞机");
                }
                $updateArray = array(
                    "table" => "plane",
                    "fieldList" => array(
                        "contacts", "address",
                        "name", "phone", "plane_type_id", "expired_at",
                        "plane_area_id", "insurance", "insurance_begin_at", "fuselage_insurance",
                        "fuselage_begin_at", "planeModel_id", "name", "company",
                        "buy_at", "warranty_at", "warranty_kilometer", "insurance_end_at", "fuselage_end_at",
                        "key_type", "key_expired_at", "key_kilometer", "key_smart_map", "key_created_at", "key_begin_kilometer"
                    ),
                    "where" => " id=$targetPlaneId ",
                    "preKey" => "key_"
                );
                $keyId = $this->getPost("key_id");
                if ($keyId) {
                    $this->updateSqlData(array(
                            "table" => "plane_key",
                            "fieldList" => array(
                                "key_type",
                                "key_expired_at",
                                "key_kilometer",
                                "key_smart_map",
                                "key_created_at",
                                "key_begin_kilometer",
                            ),
                            "where" => " id='$keyId' ",
                            "preKey" => "key_",
                            "addItems" => array("created_at" => date("Y-m-d H:i:s"))
                        )
                    );
                    $updateArray["addItems"] = array("created_at" => date("Y-m-d H:i:s"));
                }
                $this->updateSqlData($updateArray);
                $this->returnSuccess("更新成功");
            };
                break;
            default: {
                $this->view->setVars(array(
                    "planeModelList" => $this->getPlaneModelInfo(),
                    "planeTypeList" => $this->getPlaneTypeInfo(),
                    "planeAreaList" => $this->getPlaneAreaInfo(),
                    "user" => $user
                ));
            };
                break;
        }
    }


    public function doListHistoryAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->transferErrorPage("权限不足", "");
        }

        $this->checkRequestParams(array(
                array(
                    "key" => "name",
                    "type" => "presence",
                    "message" => "name param is empty"),
                array(
                    "key" => "uas_id",
                    "type" => "presence",
                    "message" => "uas_serial_id is empty"),

            )
        );
        $name = $this->getPost("name");
        $uas = $this->getPost("uas_id");
        $uasStr = "id=$uas";
        $sql = "select operation_content,user.nickname,user.phone,log.created_at from system_operation_log log left join user on user.id=log.operation_user_id
where operation_type='update_plane' and operation_content like '%$name%' and 
operation_content like \"%$uasStr%\" order by log.created_at desc";
        $data = $this->fetchAll($sql);

        for ($i = 0; $i < count($data); $i++) {
            $item = $data[$i];
            $jsonData = json_decode($item["operation_content"], true);
            $data[$i]["operation_content"] = $this->filedItemChanged("planeDetail", $name, $jsonData["field"][$name]);
        }

        $this->returnJson($data);

        //

    }

    /******************************    钥匙相关   ***********************************************************/

    public function addKeyAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError($this->lstr("OPERATION_AUTH_ERROR"));
        }
        switch ($this->getRequestAction()) {
            case $this::REQUEST_ACTION_ADD: {
                $this->checkRequestParams(array(
                    array(
                        "key" => "key_id",
                        "type" => "presence",
                        "message" => "key_id为空"),
                    array(
                        "key" => "key_data",
                        "type" => "presence",
                        "message" => "key_data为空"),
                ));
                $this->insertSqlData(array(
                    "table" => "plane_key",
                    "fieldList" => array(
                        "key_id", "key_data", "type", "expired_at", "kilomter",
                        "smart_map", "created_at", "begin_kilometer"
                    )
                ));
                $this->returnSuccess("添加成功");
            };
                break;
        }
    }

    public function listKeyAction()
    {
        if ($this->isMonitorAdminUser()) {

        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {

                $tableName = "( select k.*,p.uas_serial_id from plane_key k
left join plane p on p.id=k.plane_id where k.is_measure = 0)";
                $this->postQueryByPage(array(
                    "id" => "ID",
                    "planeModel_id" => "钥匙类型",
                    "key_id" => "钥匙ID",
                    "uas_serial_id" => "飞机序列号",
                    "kilometer" => "试用里程",
                    "unit_name" => "持有单位",
                    "phone" => "电话",
                    "contact_name" => "联系人",
                    "contact_addr" => "联系地址",
                    "remark" => "备注",
                    "created_at" => "更新时间"
                ), $tableName, array(
                    ["key_id", "like", "%", "%"],
                    ["uas_serial_id", "like", "%", "%"],
                    ["unit_name", "like", "%", "%"],
                    ["phone", "like", "%", "%"],
                    ["planeModel_id","="],
                    ["contact_name", "like", "%", "%"],
                    ["contact_addr", "like", "%", "%"],
                    ["remark", "like", "%", "%"]
                ), "planeModel_id desc,created_at desc", "id");
            };
                break;
        }
        $this->view->setVars(array("planeTypeList" => $this->getPlaneModelInfo()
            )

        );
    }


    public function detailKeyAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->transferErrorPage("权限不足", "");
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case $this::REQUEST_ACTION_DETAIL: {
                $this->checkRequestParams(array(
                    array(
                        "key" => "id",
                        "type" => "presence",
                        "message" => "请求飞机参数错误"),
                ));
                $keyId = $this->getPost("id");
                $sql = "SELECT
                                k.*, 
                                p.uas_serial_id,
                                m.name as plane_model_name
                            FROM
                                plane_key k
                            LEFT JOIN plane p ON p.id = k.plane_id
                            LEFT JOIN plane_model m ON k.planeModel_id = m.id
                            where k.id=$keyId";
                $keyData = $this->fetchOne($sql);
                $this->returnJson($keyData);
            };
                break;
            case $this::REQUEST_ACTION_UPDATE: {
                $this->checkRequestParams(array(
                    array(
                        "key" => "key_id",
                        "type" => "presence",
                        "message" => "key_id为空"),
                    array(
                        "key" => "id",
                        "type" => "presence&number",
                        "message" => "id应该为数字"),
                ));
                $uas_serial_id = $this->getPost("uas_serial_id");
                $keyId = $this->getPost("key_id");
                $id = intval($this->getPost("id"));
                if($uas_serial_id){
                    $planeId = $this->fetchColumn("select id from plane where uas_serial_id='$uas_serial_id'");

                    if (empty($planeId)) {
                        $this->returnError("不存在该飞机");
                    }
                }
                if ($id) {
                    $keyRecord=$this->fetchOne("select * from plane_key where id=$id");
                    if(!empty($keyRecord)){
                        $updateDateStr = date("Y-m-d H:i:s");
                        $unitName = $this->getPost("unit_name",$keyRecord["unit_name"]);
                        $phone = $this->getPost("phone", $keyRecord["phone"]);
                        $contactName = $this->getPost("contact_name",$keyRecord["contact_name"]);
                        $contactAddr = $this->getPost("contact_addr", $keyRecord["contact_addr"]);
                        $remark = $this->getPost("remark", $keyRecord["remark"]);
                        $expireAt = $this->getPost("expired_at",$keyRecord["expired_at"]);
                        $kilometer = $this->getPost("kilometer",$keyRecord["kilometer"]);
                        $type = $this->getPost("type",$keyRecord["type"]);
                        $beginKilometer = $this->getPost("begin_kilometer",$keyRecord["begin_kilometer"]);
                        $smartMap = $this->getPost("smart_map",$keyRecord["smart_map"]);
                        $keyData = $this->getPost("key_data",$keyRecord["key_data"]);
                        $insurance = $this->getPost("insurance",$keyRecord["insurance"]);
                        $insuranceBegin = $this->getPost("insurance_begin_at",$keyRecord["insurance_begin_at"]);
                        $insuranceEnd = $this->getPost("insurance_end_at",$keyRecord["insurance_end_at"]);
                        $this->update("plane_key", array(
                            "plane_id" => $planeId,
                            "unit_name" => $unitName,
                            "phone" => $phone,
                            "expired_at" => $expireAt,
                            "contact_name" => $contactName,
                            "contact_addr" => $contactAddr,
                            "remark" => $remark,
                            "type" => $type,
                            "expired_at" => $expireAt,
                            "kilometer" => $kilometer,
                            "begin_kilometer" => $beginKilometer,
                            "smart_map" => $smartMap,
                            "insurance"=>$insurance,
                            "insurance_begin_at"=>$insuranceBegin,
                            "insurance_end_at"=>$insuranceEnd,
                            "created_at" => $updateDateStr
                        ), "id=$id");
                        if ($planeId) {
                            $this->update("plane", array(
                                "key_id" => $keyId,
                                "type" => $type,
                                "expired_at" => $expireAt,
                                "kilometer" => $kilometer,
                                "begin_kilometer" => $beginKilometer,
                                "smart_map" => $smartMap,
                                "key_data" => $keyData,
                                "created_at" => $updateDateStr
                            ), "id=$planeId");
                        }
                    }else{
                        $this->returnError("目标ID不存在");
                    }


                    $this->returnSuccess("更新成功");


                } else {
                    $this->returnSuccess("id不存在");
                }
            };
                break;
            default: {
                $this->view->setVars(array(
                    "planeModelList" => $this->getPlaneModelInfo(),
                    "planeTypeList" => $this->getPlaneTypeInfo(),
                    "planeAreaList" => $this->getPlaneAreaInfo()));
            };
                break;
        }

    }

    /******************************    钥匙测量版    ***********************************************************/
    public function listMeasuringKeyAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->transferErrorPage("权限不足", "");
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {

                $tableName = "( select k.*,p.uas_serial_id from plane_key k
left join plane p on p.id=k.plane_id where k.is_measure = 1)";
                $this->postQueryByPage(array(
                    "id" => "ID",
                    "key_id" => "钥匙ID",
                    "uas_serial_id" => "飞机序列号",
                    "kilometer" => "试用里程",
                    "unit_name" => "持有单位",
                    "phone" => "电话",
                    "contact_name" => "联系人",
                    "contact_addr" => "联系地址",
                    "remark" => "备注",
                    "created_at" => "更新时间"
                ), $tableName, array(
                    ["key_id", "like", "%", "%"],
                    ["unit_name", "like", "%", "%"],
                    ["phone", "like", "%", "%"],
                    ["contact_name", "like", "%", "%"],
                    ["contact_addr", "like", "%", "%"],
                    ["remark", "like", "%", "%"]
                ), "planeModel_id desc,created_at desc", "id");
            };
                break;
        }
    }

    public function detailMeasuringKeyAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->transferErrorPage("权限不足", "");
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case $this::REQUEST_ACTION_DETAIL: {
                $this->checkRequestParams(array(
                    array(
                        "key" => "id",
                        "type" => "presence",
                        "message" => "请求飞机参数错误"),
                ));
                $keyId = $this->getPost("id");
                $sql = "SELECT
                                k.*, 
                                p.uas_serial_id,
                                m.name as plane_model_name
                            FROM
                                plane_key k
                            LEFT JOIN plane p ON p.id = k.plane_id
                            LEFT JOIN plane_model m ON k.planeModel_id = m.id
                            where k.id=$keyId";
                $keyData = $this->fetchOne($sql);
                $this->returnJson($keyData);
            };
                break;
            case $this::REQUEST_ACTION_UPDATE: {
                $this->checkRequestParams(array(
                    array(
                        "key" => "key_id",
                        "type" => "presence",
                        "message" => "key_id为空"),
                    array(
                        "key" => "id",
                        "type" => "presence&number",
                        "message" => "id应该为数字"),
                ));
                $uas_serial_id = $this->getPost("uas_serial_id");
                $keyId = $this->getPost("key_id");
                $id = intval($this->getPost("id"));
                if($uas_serial_id){
                    $planeId = $this->fetchColumn("select id from plane where uas_serial_id='$uas_serial_id'");

                    if (empty($planeId)) {
                        $this->returnError("不存在该飞机");
                    }
                }
                if ($id) {
                    $keyRecord=$this->fetchOne("select * from plane_key where id=$id");
                    if(!empty($keyRecord)){
                        $updateDateStr = date("Y-m-d H:i:s");
                        $unitName = $this->getPost("unit_name",$keyRecord["unit_name"]);
                        $phone = $this->getPost("phone", $keyRecord["phone"]);
                        $contactName = $this->getPost("contact_name",$keyRecord["contact_name"]);
                        $contactAddr = $this->getPost("contact_addr", $keyRecord["contact_addr"]);
                        $remark = $this->getPost("remark", $keyRecord["remark"]);
                        $expireAt = $this->getPost("expired_at",$keyRecord["expired_at"]);
                        $kilometer = $this->getPost("kilometer",$keyRecord["kilometer"]);
                        $type = $this->getPost("type",$keyRecord["type"]);
                        $beginKilometer = $this->getPost("begin_kilometer",$keyRecord["begin_kilometer"]);
                        $smartMap = $this->getPost("smart_map",$keyRecord["smart_map"]);
                        $keyData = $this->getPost("key_data",$keyRecord["key_data"]);
                        $insurance = $this->getPost("insurance",$keyRecord["insurance"]);
                        $insuranceBegin = $this->getPost("insurance_begin_at",$keyRecord["insurance_begin_at"]);
                        $insuranceEnd = $this->getPost("insurance_end_at",$keyRecord["insurance_end_at"]);
                        $this->update("plane_key", array(
                            "plane_id" => $planeId,
                            "unit_name" => $unitName,
                            "phone" => $phone,
                            "expired_at" => $expireAt,
                            "contact_name" => $contactName,
                            "contact_addr" => $contactAddr,
                            "remark" => $remark,
                            "type" => $type,
                            "expired_at" => $expireAt,
                            "kilometer" => $kilometer,
                            "begin_kilometer" => $beginKilometer,
                            "smart_map" => $smartMap,
                            "insurance"=>$insurance,
                            "insurance_begin_at"=>$insuranceBegin,
                            "insurance_end_at"=>$insuranceEnd,
                            "created_at" => $updateDateStr
                        ), "id=$id");
                        if ($planeId) {
                            $this->update("plane", array(
                                "key_id" => $keyId,
                                "type" => $type,
                                "expired_at" => $expireAt,
                                "kilometer" => $kilometer,
                                "begin_kilometer" => $beginKilometer,
                                "smart_map" => $smartMap,
                                "key_data" => $keyData,
                                "created_at" => $updateDateStr
                            ), "id=$planeId");
                        }
                    }else{
                        $this->returnError("目标ID不存在");
                    }


                    $this->returnSuccess("更新成功");


                } else {
                    $this->returnSuccess("id不存在");
                }
            };
                break;
            default: {
                $this->view->setVars(array(
                    "planeModelList" => $this->getPlaneModelInfo(),
                    "planeTypeList" => $this->getPlaneTypeInfo(),
                    "planeAreaList" => $this->getPlaneAreaInfo()));
            };
                break;
        }

    }


    /******************************    操作日志    ***********************************************************/

    public function listRecordAction()
    {
        if ($this->isMonitorAdminUser()) {

        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
                break;
            case  $this::REQUEST_ACTION_LIST: {
                $tableName = "(select * from system_operation_log where operation_type like '飞机%')";
                $this->postQueryByPage(array(
                    "operation_user_id" => "操作用户ID",
                    "operation_user_info" => "操作用户",
                    "operation_type" => "操作类型",
                    "operation_content" => "操作内容",
                    "created_at" => "操作时间"
                ), $tableName, array(
                    ["operation_user_info", "like", "%", "%"],
                    ["operation_type", "like", "%", "%"],
                    ["operation_content", "like", "%", "%"],
                    ["operation_user_id", "=", "", ""]
                ), "created_at desc", "id");
            };
                break;
        }
        $this->view->setVars(array("planeTypeList" => $this->getPlaneModelInfo()
            )

        );

    }

    public function filedItemChanged($table, $name, $value)
    {

        if ($table == "planeDetail") {
            switch ($name) {
                case "plane_area_id": {
                    $planeArea = $this->getPlaneAreaInfo(false, ture);
                    return $planeArea[$value];
                };
                    break;
                case "insurance": {
                    return $value == "1" ? "是" : "否";
                };
                    break;
                case "planeModel_id": {
                    $planeModel = $this->getPlaneModelInfo(false, true);
                    return $planeModel[$value];
                };
                    break;
                case "plane_type_id": {
                    $planeTypes = $this->getPlaneTypeInfo(false, true);
                    return $planeTypes[$value];
                };
                    break;
            }
        } else {
            switch ($name) {
                case "plane_type_name": {

                    if ($value == null) {
                        return "未知";
                    }

                };
                    break;
                case "planeModel_id": {
                    $planeModel = $this->getPlaneModelInfo(false, true);
                    $planeModelName = $planeModel[$value];
                    if (!$planeModelName) {
                        $planeModelName = "";
                    }
                    return $planeModelName;

                };
                    break;
                case "plane_type_id": {

                    $planeType = $this->getPlaneTypeInfo(false, true);
                    return $planeType[$value];
                };
                    break;
                case "insurance_end_at":
                case "fuselage_end_at": {
                    if (empty($value)) {
                        return "无";
                    } else {
//                        $now = time();
//                        $endAt = strtotime($value);
//                        $day = ceil(($endAt - $now) / 86400);
//                        if ($day >= 0) {
//                            return "剩余" . $day . "天";
//                        } else {
//                            return "超出" . (-$day) . "天";
//                        }
                    }
                };
                    break;
                case "type": {
                    return $value == "1" ? "混合证书" : "无限期";
                };
                    break;
                case "online": {
                    return $value == "1" ? "可用" : "不可用";
                };
                    break;
                case "unit_name":
                case "contact_name":
                case "contact_addr":
                case "remark":
                case "kilometer":
                case "created_at":
                case "uas_serial_id":
                case "name":
                case "phone":
                case "uas_odometer_value":
                case "plane_model_name":
                case "city":
                case "company":
                case "nickname": {
                    if ($value == null) {
                        return "";
                    }
                };
                    break;
            }
        }

        return $value;
    }
    
    public function keyUnbindAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError("操作权限错误");
        }
        $action = $this->getRequestAction();
        switch ($action) {
            case  $this::REQUEST_ACTION_DELETE: {
            };
            break;
            case  $this::REQUEST_ACTION_LIST: {
                $table = "(SELECT * from plane where (planeModel_id=3 or planeModel_id=8))";
                $this->postQueryByPage(array(
                        "id" => "id",
                        "name" => "持有单位",
                        "uas_serial_id" => "飞机编号",
                        "planeModel_id" => "飞机类型",
                        "key_id" => "钥匙ID",
                        "phone" => "联系电话",
                        
                ), $table, array(
                        ["key_id", "=", "", ""]
                ), "created_at desc", "id");
            };
            break;
        }
    }
    
    public function keyUnbindByIdAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError("操作权限错误");
        }
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "unbind ".json_encode($_POST)."\r\n", FILE_APPEND);
        $this->checkRequestParams(array(
                array(
                        "key" => "id",
                        "type" => "presence",
                        "message" => "id为空",
                ),
        ));
        
        $id = $this->getPost("id");
        file_put_contents("./log_" . date("Y-m-d") . ".txt", "\n" . date("H:i:s", time()) . ':' . __METHOD__ . ':' . "unbind id:$id\r\n", FILE_APPEND);
        
        $sql = "select id,key_id,planeModel_id from plane where id = $id";
        $plane = $this->fetchOne($sql);
        if(empty($plane)){
            $this->returnResponse(4,"没有飞机");
        }elseif($plane['planeModel_id']=='3'||$plane['planeModel_id']=='8'){
            $this->update('plane', array('key_id'=>null), "id=$id");
            if(!empty($plane['key_id'])){
                $sql = "select id,plane_id from plane_key where key_id = '{$plane['key_id']}'";
                $key = $this->fetchOne($sql);
                if($id==$key['plane_id'])
                    $this->update('plane_key', array('plane_id'=>null), "id={$key['id']}");
            }
            $this->returnResponse(0, "架解绑成功", $plane['key_id']);
        }else{
            $this->returnResponse(4,"飞机类型错误");
        }
        
    }
    
    public function doKeyUnbindAction()
    {
        if (!$this->isMonitorAdminUser()) {
            $this->returnError("操作权限错误");
        }
        $key_id = $this->getPost('key_id');
        if(!empty($key_id)){
            $sql = "select id from plane where key_id = '$key_id' and (planeModel_id=3 or planeModel_id=8) ";
            $planes = $this->fetchAll($sql);
            $i = 0;
            if(empty($planes)){
                $this->returnResponse(4,"key_id 未绑定D1000飞机",'');
            }else{
                foreach ($planes as $plane){
                    $ids[] = $plane['id'];
                    $this->update('plane', array('key_id'=>null), "id={$plane['id']} and key_id='$key_id'");
                    $i++;
                }
            }
            $this->update('plane_key', array('plane_id'=>null), "key_id='$key_id' and (planeModel_id=3 or planeModel_id=8)");
            
            $this->returnResponse(0, $i."架解绑成功", $ids);
        }
    }
}